/**
 * 习惯管理状态模块
 * 管理习惯列表、完成状态、统计数据等
 */

import { defineStore } from 'pinia/dist/pinia.mjs'
import { habitsApi } from '@/api'

export const useHabitsStore = defineStore('habits', {
  state: () => ({
    // 习惯列表
    habitsList: [],
    // 当前选中的习惯
    currentHabit: null,
    // 习惯统计数据
    statsData: {
      totalHabits: 0,
      completedToday: 0,
      completionRate: 0,
      streak: 0
    },
    // 加载状态
    loading: {
      list: false,
      detail: false,
      stats: false,
      action: false
    },
    // 筛选和排序
    filters: {
      status: 'all', // all, active, completed
      category: 'all',
      sortBy: 'created_at', // created_at, name, priority
      sortOrder: 'desc' // asc, desc
    },
    // 分页信息
    pagination: {
      current: 1,
      pageSize: 20,
      total: 0,
      hasMore: true
    }
  }),

  getters: {
    // 获取今日习惯列表
    todayHabits: (state) => {
      const today = new Date().toDateString()
      return state.habitsList.filter(habit => {
        return habit.schedule && habit.schedule.includes(new Date().getDay())
      })
    },
    
    // 获取已完成的习惯
    completedHabits: (state) => {
      return state.habitsList.filter(habit => habit.completed_today)
    },
    
    // 获取未完成的习惯
    pendingHabits: (state) => {
      return state.habitsList.filter(habit => !habit.completed_today)
    },
    
    // 按分类分组的习惯
    habitsByCategory: (state) => {
      const grouped = {}
      state.habitsList.forEach(habit => {
        const category = habit.category || '未分类'
        if (!grouped[category]) {
          grouped[category] = []
        }
        grouped[category].push(habit)
      })
      return grouped
    },
    
    // 获取筛选后的习惯列表
    filteredHabits: (state) => {
      let filtered = [...state.habitsList]
      
      // 按状态筛选
      if (state.filters.status === 'active') {
        filtered = filtered.filter(habit => habit.status === 'active')
      } else if (state.filters.status === 'completed') {
        filtered = filtered.filter(habit => habit.completed_today)
      }
      
      // 按分类筛选
      if (state.filters.category !== 'all') {
        filtered = filtered.filter(habit => habit.category === state.filters.category)
      }
      
      // 排序
      filtered.sort((a, b) => {
        const { sortBy, sortOrder } = state.filters
        let aValue = a[sortBy]
        let bValue = b[sortBy]
        
        if (sortBy === 'name') {
          aValue = aValue?.toLowerCase() || ''
          bValue = bValue?.toLowerCase() || ''
        }
        
        if (sortOrder === 'asc') {
          return aValue > bValue ? 1 : -1
        } else {
          return aValue < bValue ? 1 : -1
        }
      })
      
      return filtered
    }
  },

  actions: {
    /**
     * 获取习惯列表
     * @param {Object} params 查询参数
     * @param {Boolean} refresh 是否刷新
     */
    async getHabitsList(params = {}, refresh = false) {
      if (refresh) {
        this.pagination.current = 1
        this.pagination.hasMore = true
      }
      
      if (!this.pagination.hasMore && !refresh) {
        return
      }
      
      this.loading.list = true
      try {
        const queryParams = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.filters,
          ...params
        }
        
        const response = await habitsApi.getHabitsList(queryParams)
        const { data, pagination } = response.data
        
        if (refresh) {
          this.habitsList = data
        } else {
          this.habitsList.push(...data)
        }
        
        this.pagination = {
          ...this.pagination,
          ...pagination,
          hasMore: data.length === this.pagination.pageSize
        }
        
        return response
      } catch (error) {
        console.error('获取习惯列表失败:', error)
        throw error
      } finally {
        this.loading.list = false
      }
    },

    /**
     * 创建习惯
     * @param {Object} habitData 习惯数据
     */
    async createHabit(habitData) {
      this.loading.action = true
      try {
        const response = await habitsApi.createHabit(habitData)
        const newHabit = response.data
        
        // 添加到列表开头
        this.habitsList.unshift(newHabit)
        this.updateStatsData()
        
        return response
      } catch (error) {
        console.error('创建习惯失败:', error)
        throw error
      } finally {
        this.loading.action = false
      }
    },

    /**
     * 更新习惯
     * @param {String} id 习惯ID
     * @param {Object} habitData 习惯数据
     */
    async updateHabit(id, habitData) {
      this.loading.action = true
      try {
        const response = await habitsApi.updateHabit(id, habitData)
        const updatedHabit = response.data
        
        // 更新列表中的习惯
        const index = this.habitsList.findIndex(habit => habit.id === id)
        if (index !== -1) {
          this.habitsList[index] = updatedHabit
        }
        
        // 更新当前习惯
        if (this.currentHabit && this.currentHabit.id === id) {
          this.currentHabit = updatedHabit
        }
        
        return response
      } catch (error) {
        console.error('更新习惯失败:', error)
        throw error
      } finally {
        this.loading.action = false
      }
    },

    /**
     * 删除习惯
     * @param {String} id 习惯ID
     */
    async deleteHabit(id) {
      this.loading.action = true
      try {
        await habitsApi.deleteHabit(id)
        
        // 从列表中移除
        this.habitsList = this.habitsList.filter(habit => habit.id !== id)
        
        // 清除当前习惯
        if (this.currentHabit && this.currentHabit.id === id) {
          this.currentHabit = null
        }
        
        this.updateStatsData()
        
        return true
      } catch (error) {
        console.error('删除习惯失败:', error)
        throw error
      } finally {
        this.loading.action = false
      }
    },

    /**
     * 获取习惯详情
     * @param {String} id 习惯ID
     */
    async getHabitDetail(id) {
      this.loading.detail = true
      try {
        const response = await habitsApi.getHabitDetail(id)
        this.currentHabit = response.data
        return response
      } catch (error) {
        console.error('获取习惯详情失败:', error)
        throw error
      } finally {
        this.loading.detail = false
      }
    },

    /**
     * 标记习惯完成
     * @param {String} id 习惯ID
     * @param {Object} data 完成数据
     */
    async markHabitComplete(id, data = {}) {
      try {
        const response = await habitsApi.markHabitComplete(id, {
          date: new Date().toISOString().split('T')[0],
          ...data
        })
        
        // 更新本地状态
        const habit = this.habitsList.find(h => h.id === id)
        if (habit) {
          habit.completed_today = true
          habit.completion_count = (habit.completion_count || 0) + 1
          habit.current_streak = (habit.current_streak || 0) + 1
        }
        
        this.updateStatsData()
        
        return response
      } catch (error) {
        console.error('标记习惯完成失败:', error)
        throw error
      }
    },

    /**
     * 取消习惯完成
     * @param {String} id 习惯ID
     * @param {Object} data 取消数据
     */
    async unmarkHabitComplete(id, data = {}) {
      try {
        const response = await habitsApi.unmarkHabitComplete(id, {
          date: new Date().toISOString().split('T')[0],
          ...data
        })
        
        // 更新本地状态
        const habit = this.habitsList.find(h => h.id === id)
        if (habit) {
          habit.completed_today = false
          habit.completion_count = Math.max((habit.completion_count || 0) - 1, 0)
          habit.current_streak = Math.max((habit.current_streak || 0) - 1, 0)
        }
        
        this.updateStatsData()
        
        return response
      } catch (error) {
        console.error('取消习惯完成失败:', error)
        throw error
      }
    },

    /**
     * 获取习惯统计数据
     * @param {Object} params 查询参数
     */
    async getHabitStats(params = {}) {
      this.loading.stats = true
      try {
        const response = await habitsApi.getHabitStats(params)
        this.statsData = { ...this.statsData, ...response.data }
        return response
      } catch (error) {
        console.error('获取习惯统计失败:', error)
        throw error
      } finally {
        this.loading.stats = false
      }
    },

    /**
     * 更新筛选条件
     * @param {Object} filters 筛选条件
     */
    updateFilters(filters) {
      this.filters = { ...this.filters, ...filters }
      // 重新获取数据
      this.getHabitsList({}, true)
    },

    /**
     * 重置筛选条件
     */
    resetFilters() {
      this.filters = {
        status: 'all',
        category: 'all',
        sortBy: 'created_at',
        sortOrder: 'desc'
      }
      this.getHabitsList({}, true)
    },

    /**
     * 更新统计数据（本地计算）
     */
    updateStatsData() {
      const totalHabits = this.habitsList.length
      const completedToday = this.completedHabits.length
      const completionRate = totalHabits > 0 ? (completedToday / totalHabits * 100).toFixed(1) : 0
      
      this.statsData = {
        ...this.statsData,
        totalHabits,
        completedToday,
        completionRate: parseFloat(completionRate)
      }
    },

    /**
     * 清空数据
     */
    clearData() {
      this.habitsList = []
      this.currentHabit = null
      this.statsData = {
        totalHabits: 0,
        completedToday: 0,
        completionRate: 0,
        streak: 0
      }
      this.pagination = {
        current: 1,
        pageSize: 20,
        total: 0,
        hasMore: true
      }
    }
  },

  // 持久化配置
  persist: {
    key: 'habits-store',
    paths: ['habitsList', 'statsData', 'filters']
  }
})